package com.apache.info.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SystemTools;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.info.entity.PubMetadata;
import com.apache.info.entity.PubSortInfo;
import com.apache.info.manager.PubMetadataManager;

public class PubMetadataManagerImpl implements PubMetadataManager {

	protected IDao pubMetadataDao;
	protected final String entityName = "com.apache.info.entity.PubMetadata";
	protected Map<String, PluginConnector> plugins = new HashMap<String, PluginConnector>();

	public void setPubMetadataDao(IDao pubMetadataDao) {
		this.pubMetadataDao = pubMetadataDao;
	}

	public String saveInfo(ParamsVo<PubMetadata> vo) throws BusinessException {
		PubMetadata pubMetadata = vo.getObj();
		String infoId = Validator.generate();
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="pubMetadata_"+infoId;
		pubMetadata.setMetadataId(infoId);
		MethodParam param = new MethodParam("PubMetadata", cacheKey, "", entityName);
		param.setVaule(pubMetadata);
		if (Validator.isEmpty(pubMetadata.getIfAdd()))
			pubMetadata.setIfAdd("F");
		if (Validator.isEmpty(pubMetadata.getIfEdit()))
			pubMetadata.setIfEdit("F");
		if (Validator.isEmpty(pubMetadata.getIfList()))
			pubMetadata.setIfList("F");
		if (Validator.isEmpty(pubMetadata.getIfSearch()))
			pubMetadata.setIfSearch("F");
		if (pubMetadataDao.insert(param)) {
			ParamsVo pvo = new ParamsVo();
			pvo.setParams("sortId", pubMetadata.getSortId());
			pvo.setParams("metadata", pubMetadata);
			cacheInfo(pubMetadata.getSortId(), pubMetadata, "add", null);
			if (!Validator.isEmpty(plugins.get("updateTable"))) {//添加表字段
				try {
					plugins.get("updateTable").execute(pvo);
				} catch (Exception e) {
					throw new BusinessException("动态修改数据[" + pubMetadata.getDataShortName() + "]字段出错", e);
				}
			}
			return infoId;
		}
		return "";
	}

	public boolean editInfo(ParamsVo<PubMetadata> vo) throws BusinessException {
		PubMetadata pubMetadata = vo.getObj();
		if (Validator.isNotNull(pubMetadata.getMetadataId())) {
			String cacheKey = "";
			//String cacheKey="pubMetadata_"+pubMetadata.getMetadataId();
			MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
			param.setInfoId(pubMetadata.getMetadataId());
			PubMetadata mp = (PubMetadata) pubMetadataDao.selectById(param);
			param = new MethodParam("PubMetadata", cacheKey, "", entityName);
			param.setVaule(pubMetadata);
			boolean mark = pubMetadataDao.edit(param);
			if (mark) {
				cacheInfo(pubMetadata.getSortId(), pubMetadata, "edit", mp);
				if (!mp.getDataLength().equals(pubMetadata.getDataLength())
						|| !mp.getDataShortName().equalsIgnoreCase(pubMetadata.getDataShortName())) {
					ParamsVo pvo = new ParamsVo();
					pvo.setParams("sortId", pubMetadata.getSortId());
					pvo.setParams("metadata", pubMetadata);
					pvo.setParams("old", mp);
					pvo.setMethodKey("modify");
					if (!Validator.isEmpty(plugins.get("updateTable"))) {//修改表字段
						try {
							plugins.get("updateTable").execute(pvo);
						} catch (Exception e) {
							throw new BusinessException("动态修改数据[" + pubMetadata.getDataShortName() + "]字段出错", e);
						}
					}
				}
			}
			return mark;
		}
		return false;
	}

	public boolean deleteInfo(ParamsVo<PubMetadata> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			return false;
		}
		String cacheKey = "";
		//String cacheKey="pubMetadata_"+infoId;
		//	String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		PubMetadata mp = (PubMetadata) pubMetadataDao.selectById(param);
		if ("1".equals(mp.getDataRestrict())) {
			return false;
		}
		param.setInfoId("");
		param.setParams("metadataId", infoId);
		param.setDelete(true);
		boolean mark = pubMetadataDao.delete(param);
		if (mark) {
			cacheInfo(mp.getSortId(), mp, "del", null);
			ParamsVo pvo = new ParamsVo();
			pvo.setParams("sortId", mp.getSortId());
			pvo.setParams("metadata", mp);
			pvo.setMethodKey("del");
			if (!Validator.isEmpty(plugins.get("updateTable"))) {//修改表字段
				try {
					plugins.get("updateTable").execute(pvo);
				} catch (Exception e) {
					throw new BusinessException("动态删除数据[" + mp.getDataShortName() + "]字段出错", e);
				}
			}
		}
		return mark;
	}

	private void cacheInfo(String sortInfoCode, PubMetadata pubMetadata, String type, PubMetadata old) {
		if (Validator.isNull(pubMetadata.getDataAttr()) || Validator.isNull(pubMetadata.getDataShortName()))
			return;
		String key = sortInfoCode + "_tableAttr";
		String content = String.valueOf(SystemTools.getInstance().getCache("").getCacheObjectByKey(key));
		String str[];
		if (Validator.isNull(content)) {
			String cacheKey = "pubSortInfo_" + sortInfoCode;
			MethodParam param = new MethodParam("ById", cacheKey, "", PubSortInfo.class.getName());
			param.setInfoId(sortInfoCode);
			PubSortInfo info = (PubSortInfo) pubMetadataDao.selectById(param);
			str = new String[4];
			str[0] = key;
			if ("subId".equals(pubMetadata.getDataAttr())) {
				str[1] = pubMetadata.getDataAttr();
				str[2] = "sub_id";
			} else {
				str[1] = "";
				str[2] = "info_id";
			}
			str[3] = info.getInfoTableName();
		} else {
			str = content.split(";");
		}
		if ("1".equals(pubMetadata.getDataRestrict())) {
			str[2] = pubMetadata.getDataShortName();
		}
		if ("add".equals(type)) {
			str[1] = str[1] + "," + pubMetadata.getDataAttr();
		} else if ("edit".equals(type)) {
			if (str[1].indexOf(old.getDataAttr()) == -1) {
				str[1] = str[1] + "," + pubMetadata.getDataAttr();
				str[1] = str[1].replace(pubMetadata.getDataAttr(), "");
				str[1] = str[1].replace(",,", ",");
			} else {
				str[1] = str[1] + "," + pubMetadata.getDataAttr();
				str[1] = str[1].replace(old.getDataAttr() + ",", "");
			}
		} else {
			str[1] = str[1].replace(pubMetadata.getDataAttr() + ",", "");
		}
		String cacheContent = str[0] + ";" + str[1] + ";" + str[2] + ";" + str[3];
		SystemTools.getInstance().getCache("").createCacheObject(key, cacheContent);
	}

	public Object getInfoById(ParamsVo<PubMetadata> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="pubMetadata_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return pubMetadataDao.selectById(param);
	}

	public Object execute(ParamsVo<PubMetadata> vo) {
		String key = vo.getKey();
		if ("ForeignKey".equals(key)) {
			return getForeignKeyS(vo);
		} else if ("initCache".equalsIgnoreCase(key)) {
			pubMetadataDao.initSystemCache();
		}
		return null;
	}

	private List getForeignKeyS(ParamsVo<PubMetadata> vo) {
		MethodParam param = setMethodParams(vo, 2);
		param.setKey("ByForeignKey");
		return pubMetadataDao.select(param);
	}

	public Page getPageInfo(ParamsVo<PubMetadata> vo) {
		MethodParam param = setMethodParams(vo, 2);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		Page page = pubMetadataDao.pageSelect(param);
		return page;
	}

	public List<PubMetadata> getList(ParamsVo<PubMetadata> vo) {
		MethodParam param = setMethodParams(vo, 2);
		return pubMetadataDao.select(param);
	}

	public long countInfo(ParamsVo<PubMetadata> vo) {
		MethodParam param = setMethodParams(vo, 1);
		return pubMetadataDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<PubMetadata> vo, int type) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		PubMetadata pubMetadata = vo.getObj();
		if (Validator.isNotNull(pubMetadata.getSortId())) {
			param.setParams("sortId", pubMetadata.getSortId());
		}
		if (Validator.isNotNull(pubMetadata.getDataFullName())) {
			param.setParams("dataFullName", pubMetadata.getDataFullName());
		}
		if (Validator.isNotNull(pubMetadata.getDataShortName())) {
			param.setParams("dataShortName", pubMetadata.getDataShortName());
		}
		if (Validator.isNotNull(pubMetadata.getDataRestrict())) {
			param.setParams("dataRestrict", pubMetadata.getDataRestrict());
		}
		if (Validator.isNotNull(pubMetadata.getForeignKeyName())) {
			param.setParams("foreignKeyName", pubMetadata.getForeignKeyName());
		}
		if (Validator.isNotNull(pubMetadata.getReserved1())) {
			param.setParams("reserved1", pubMetadata.getReserved1());
		}
		if (Validator.isNotNull(pubMetadata.getReserved2())) {
			param.setParams("reserved2", pubMetadata.getReserved2());
		}
		if (Validator.isNotNull(pubMetadata.getReserved3())) {
			param.setParams("reserved3", pubMetadata.getReserved3());
		}
		return param;
	}

	public void setPlugins(Map<String, PluginConnector> plugins) {
		this.plugins = plugins;
	}
}
